<template>
    <div class="view_tracker_restocking">
        <card title="传感器补货">
            <template #actions>
                <el-select class="w-28" v-model="queryBy">
                    <el-option v-for="(val, key) in queryBySomething" :key="key" :value="key" :label="val" />
                </el-select>
                <el-input
                    class="w-48"
                    v-model="queryString"
                    :placeholder="placeholder"
                    prefix-icon="el-icon-search"
                    clearable
                />
                <el-button type="primary" @click="add">添加补货订单</el-button>
            </template>

            <template #default>
                <el-table :data="tableData">
                    <el-table-column type="index" label="#" align="center" />
                    <el-table-column prop="sellerName" label="店铺名称" />
                    <el-table-column prop="replenishSn" label="补货单号" />
                    <el-table-column prop="quantity" label="数量" />
                    <el-table-column prop="orderType" label="订单类型">
                        <template #default="{ row: { orderType } }">
                            <el-tag :type="trackerOrderTypesForRestocked[orderType].tagType">
                                {{ trackerOrderTypesForRestocked[orderType].text }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="订单状态">
                        <template #default="{ row: { orderStatus } }">
                            <el-tag effect="dark" :type="trackerOrderStatusForRestocked[orderStatus].tagType">
                                {{ trackerOrderStatusForRestocked[orderStatus].text }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" />
                    <el-table-column label="操作">
                        <template #default="{ row }">
                            <!-- 为待发货状态显示发货按钮 -->
                            <el-button type="text" v-if="row.orderStatus === 1" @click="openDeliveryDialog(row)">
                                发货
                            </el-button>
                            <el-button type="text" @click="view(row.trackerOrderId)">查看详情</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>

            <template #bottom-right>
                <el-pagination
                    @current-change="query"
                    :currentPage.sync="currentPage"
                    :total="total"
                    :pageSize="pageSize"
                />
            </template>
        </card>

        <!-- 待补货店铺列表对话框 -->
        <el-dialog :visible.sync="visible" title="待补货店铺列表" custom-class="unrestocked_shop">
            <unrestocked-shop-table ref="unrestockedShopTable" @restock="openRestockingDialog"></unrestocked-shop-table>
        </el-dialog>

        <!-- 补货对话框 -->
        <el-dialog
            :visible.sync="visible2"
            title="店铺补货"
            custom-class="restocking_dialog"
            @closed="handleRestockingDialogClosed"
        >
            <template #default>
                <el-alert>
                    <p>店铺名：{{ restockingFormData.sellerName }}</p>
                    <p>收货人：{{ restockingFormData.receiverName }}</p>
                    <p>收货人手机号码：{{ restockingFormData.receiverPhone }}</p>
                    <p>收货地址：{{ restockingFormData.receiverAddress }}</p>
                    <p>补货数量：{{ restockingFormData.quantity }}</p>
                </el-alert>
                <div class="input_box">
                    <div class="input_box-label">传感器</div>
                    <textarea v-model="restockingFormData.vid" class="input_box-control" rows="5" />
                </div>
            </template>
            <template #footer>
                <el-button type="primary" @click="restock">补货</el-button>
            </template>
        </el-dialog>

        <!-- 发货对话框 -->
        <el-dialog
            :visible.sync="visible3"
            title="传感器发货"
            custom-class="delivery_dialog"
            @closed="handleDeliveryDialogClosed"
        >
            <template #default>
                <el-alert>
                    <p>必须是以8开头的15位数字，以英文逗号分隔，或回车换行</p>
                </el-alert>
                <el-alert type="success">
                    <p>当前订单需要补{{ deliveryFormData.orderTrackerQuantify }}个传感器</p>
                </el-alert>
                <div class="input_box">
                    <label class="input_box-label">物流公司</label>
                    <input class="input_box-control" type="text" v-model="deliveryFormData.deliveryCompany" />
                </div>
                <div class="input_box">
                    <label class="input_box-label">物流单号</label>
                    <input class="input_box-control" type="text" v-model="deliveryFormData.deliverySn" />
                </div>
            </template>
            <template #footer>
                <el-button type="primary" @click="deliver">发货</el-button>
            </template>
        </el-dialog>

        <!-- 订单详情对话框 -->
        <el-dialog :visible.sync="visible4" custom-class="details_dialog">
            <template #default>
                <div class="desc_list">
                    <div class="desc_list-top">
                        <h1 class="desc_list-title">{{ details.trackerOrderSn }}</h1>
                        <p class="desc_list-subtitle">店铺名：{{ details.shopName }}</p>
                    </div>
                    <dl class="desc_list-content">
                        <div class="desc_list-item">
                            <dt>数量</dt>
                            <dd>{{ details.quantity }}</dd>
                        </div>
                        <div class="desc_list-item">
                            <dt>类型</dt>
                            <dd>{{ trackerOrderTypesForRestocked[details.orderType].text }}</dd>
                        </div>
                        <div class="desc_list-item">
                            <dt>创建类型</dt>
                            <dd>{{ details.createTime }}</dd>
                        </div>
                        <div class="desc_list-item">
                            <dt>收货人</dt>
                            <dd>{{ details.receiverName }}</dd>
                        </div>
                        <div class="desc_list-item">
                            <dt>收货人电话号码</dt>
                            <dd>{{ details.receiverPhone }}</dd>
                        </div>
                        <div class="desc_list-item">
                            <dt>收货地址</dt>
                            <dd>{{ details.receiverAddress }}</dd>
                        </div>
                        <div class="desc_list-item">
                            <dt>物流名称</dt>
                            <dd>{{ details.deliveryCompany }}</dd>
                        </div>
                        <div class="desc_list-item">
                            <dt>物流单号</dt>
                            <dd>{{ details.deliverySn }}</dd>
                        </div>
                        <div class="desc_list-item">
                            <dt>发货时间</dt>
                            <dd>{{ details.deliveryTime }}</dd>
                        </div>
                        <div class="desc_list-item">
                            <dt>发货时间</dt>
                            <el-table :data="details.vidList">
                                <el-table-column type="index" label="#" align="center" />
                                <el-table-column prop="trackerVid" label="传感器编号" />
                                <el-table-column prop="trackerStatus" label="使用状态">
                                    <template #default="{ row }">
                                        {{ trackerUsageStatus[row.trackerStatus] }}
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </dl>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { getQueryOptions } from '../../mixins';
import unrestockedShopTable from './tracker_unrestocked_shop_table';

export default {
    data() {
        return {
            tableData: [],
            descriptionList: {},

            visible: false,
            visible2: false,
            visible3: false,
            visible4: false,

            // 补货表单数据
            restockingFormData: {
                vid: '',
                sellerId: '',
                sellerName: '',
                quantity: '',
                receiverName: '',
                receiverPhone: '',
                receiverAddress: '',
                price: 10,
            },

            // 发货表单数据
            deliveryFormData: {
                deliveryCompany: '',
                deliverySn: '',
                orderTrackerQuantify: '',
            },

            queryBy: 'vid',

            // 未补货的店铺
            unrestockedShops: [],
            // 未补货的店铺查询字符串
            unrestockedShopQueryString: '',

            // 订单详情
            details: {},
        };
    },

    mixins: [
        getQueryOptions({
            apiurl: '/yxl/platform/findReplenishment',
            paginable: true,
            params: {
                queryString: 'queryBy',
            },
        }),
    ],

    components: { unrestockedShopTable },

    computed: {
        // 按某物查询
        queryBySomething() {
            return {
                vid: '传感器vid',
                orderSn: '订单号',
            };
        },

        // 搜索框占位符
        placeholder() {
            return `按${this.queryBySomething[this.queryBy]}查询`;
        },

        // >>>>> 补货的传感器订单类型（与普通传感器订单类型保持一致） <<<<<
        trackerOrderTypesForRestocked() {
            return {
                1: { text: '免租' },
                2: { text: '押金', tagType: 'success' },
                3: { text: '补货', tagType: 'warning' },
                4: { text: '退货', tagType: 'danger' },
            };
        },

        // >>>>> 补货的传感器订单状态 <<<<<
        trackerOrderStatusForRestocked() {
            return {
                1: { text: '待发货', tagType: 'warning' },
                2: { text: '已发货' },
                3: { text: '已完成', tagType: 'success' },
            };
        },

        // >>>>> 传感器使用状态 <<<<<
        trackerUsageStatus() {
            return {
                1: '未使用',
                2: '已使用',
                3: '已退',
            };
        },
    },

    methods: {
        // 新增补货
        add() {
            this.visible = true;
        },

        // 打开补货对话框
        openRestockingDialog(row) {
            this.restockingFormData.sellerId = row.sellerId;
            this.restockingFormData.receiverName = row.name;
            this.restockingFormData.receiverPhone = row.phone;
            this.restockingFormData.receiverAddress = row.address;
            this.restockingFormData.sellerName = row.sellerName;
            this.restockingFormData.quantity = row.number;

            this.visible2 = true;
        },

        // 打开发货对话框
        openDeliveryDialog(row) {
            this.deliveryFormData.trackerOrderId = row.trackerOrderId;
            this.deliveryFormData.orderTrackerQuantify = row.quantity;

            this.visible3 = true;
        },

        // 处理补货对话框关闭
        handleRestockingDialogClosed() {
            this.restockingFormData.vid = '';
        },

        // 处理发货对话框关闭
        handleDeliveryDialogClosed() {
            this.deliveryFormData.deliveryCompany = '';
            this.deliveryFormData.deliverySn = '';
        },

        // 验证传感器id格式
        // 如果格式不正确给出对应提示并返回false，如果格式正确返回格式化后的id列表
        verifyTrackersIdFormat(vid) {
            if (vid.includes('\n') && vid.includes(',')) {
                this.$message.error('回车换行不需要带逗号');
                return;
            }

            if (!/^(8\d{14},?)+\b$/.test((vid = vid.replace(/\n/g, ',')))) {
                this.$message.error('传感器id格式不正确');
                return;
            }

            return true;
        },

        // 补货
        restock() {
            let data = Object.assign({}, this.restockingFormData);
            data.vid = data.vid.trim();
            if (this.verifyTrackersIdFormat(data.vid)) {
                this.$put('/yxl/platform/saveReplenishment', data).then(res => {
                    this.visible2 = false;
                    // 补货成功自动刷新数据
                    this.$refs.unrestockedShopTable.query();
                    this.query();
                });
            }
        },

        // 发货
        deliver() {
            this.$post('/yxl/platform/delivery', this.deliveryFormData).then(res => {
                this.query();

                this.visible3 = true;
            });
        },

        // 查看详情
        view(trackerOrderId) {
            this.$get('/yxl/platform/findReplenishmentDetails', { trackerOrderId }).then(res => {
                this.details = Object.freeze(res);

                this.visible4 = true;
            });
        },
    },
};
</script>